package xin.yogee.ms.module.sys.controller;


import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import xin.yogee.ms.common.BaseController;
import xin.yogee.ms.module.sys.entity.SysDepartment;
import xin.yogee.ms.module.sys.service.ISysDepartmentService;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 工作部门 前端控制器
 * </p>
 *
 * @author jackieQ
 * @since 2019-02-14
 */
@RestController
@RequestMapping("/yl/ylDepartment")
public class SysDepartmentController extends BaseController {

    @Autowired
    private ISysDepartmentService iYlDepartmentService;

    @RequestMapping(value = "/get")
    public String get(@RequestBody JSONObject json){
        String id = json.getString("id");
        SysDepartment depart = iYlDepartmentService.getByDepartId(id);
        return successJson("success",depart,"获取成功");
    }

    @RequestMapping(value = "/list")
    public String list(){
        List<SysDepartment> departList = iYlDepartmentService.getList();
        return successJson("success",departList,"获取成功");
    }

    @RequestMapping(value = "/treeList")
    public String treeList(){
        List<SysDepartment> departList = iYlDepartmentService.list();
        return treeList(departList);
    }

    @RequestMapping(value = "/store")
    @ResponseBody
    public String store(SysDepartment ylDepartment, @RequestBody JSONObject json){
        String id = json.getString("id");
        String name = json.getString("name");
        String pid = json.getString("pid");
        String startWork = json.getString("startWork");
        String endWork = json.getString("endWork");
        String leaderId = json.getString("leaderId");
        SysDepartment pDepartment = iYlDepartmentService.getById(pid);
        ylDepartment.setId(id);
        ylDepartment.setStartWork(startWork);
        ylDepartment.setEndWork(endWork);
        ylDepartment.setName(name);
        ylDepartment.setPid(pid);
        //拼接上级部门的所有上级加上当前上级部门的id，为新建部门的所有上级部门
        //如果是顶级部门不拼接
        if ("Y".equals(pDepartment.getId())){
            ylDepartment.setPids(pid);
        }else {
            ylDepartment.setPids(pDepartment.getPids() + "," + pid);
        }
        ylDepartment.setName(name);
        ylDepartment.setLeaderId(leaderId);
        iYlDepartmentService.saveOrUpdate(ylDepartment);
        //修改当前部门的上级部门isLast状态为0
        //如果是顶级部门跳过
        if (!"0".equals(pDepartment.getIsLast())){
            pDepartment.setIsLast("0");
            iYlDepartmentService.updateById(pDepartment);
        }
        return successJson("success", new HashMap(0), "创建成功");
    }

    @RequestMapping(value = "/del")
    public String del(@RequestBody JSONObject json){
        String id = json.getString("departId");
        iYlDepartmentService.removeById(id);
        return successJson("success","","删除成功");
    }
}
